"""
使用python链接redis
# 1、导包
"""

import redis
import time

# 创建链接
redis_conn = redis.Redis(db=5)

"""
redis数据类型：
    字符串(string)、 列表(list)、 哈希(hash)、集合(set)、有序集合(sortedset) 

redis是一个NoSQL, 它是key， value形式存在，  它是基于内存，读写速度快，可持久化
"""

# 字符串
# set(name, value)    创建数据
# redis_conn.set('username', 'zhangsan')

# get(name)   获取数据
# print(redis_conn.get('username').decode())

# setex(name, time, value)  创建一个带有时间效果的key
# redis_conn.setex('age', 10, 18)
# print(redis_conn.get('age'))
# time.sleep(11)
# print(redis_conn.get('age'))

# 增量    incr(name, amount=1)   incr 没有name会自动创建，有name，自动+1
# redis_conn.incr('number')
# print(redis_conn.get('number'))

# 哈希   hash      hset hget
# 创建一个哈希的键值对 {user1: {name: zhangsan, age: 18}, user2: {name: lisi, age: 20}}
"""
使用hash类型来做购物车
    user_id goods_id goods_num

"""

user1 = '1'
goods_id1 = '1'
goods_num1 = 2
goods_id3 = '3'
goods_num3 = 4

user2 = '2'
goods_id2= '2'
goods_num2 = 2
goods_id4 = '4'
goods_num4 = 4

# # redis_conn.hset(user1, goods_id1, goods_num1)
# # redis_conn.hset(user1, goods_id3, goods_num3)
# redis_conn.hset(user2, goods_id2, goods_num2)
# redis_conn.hset(user2, goods_id4, goods_num4)
# hgetall(name)  获取当前name下的所有的key和value
# print(redis_conn.hgetall(user1))
# print(redis_conn.hgetall(user2))

# hincrby(name, key, amount)  哈希自增量    没有name和key时，自动创建   否则是自增加amount
# redis_conn.hincrby(user2, goods_id2, goods_num2)
# redis_conn.hincrby(user2, goods_id4, goods_num4)
# print(redis_conn.hgetall(user2))


# redis_conn.hdel(user2, goods_id2)

# print(redis_conn.hget(user2, goods_id2))
# redis_conn.delete(user2)
# print(redis_conn.hgetall(user2))


# # 有序集合  zincrby(name, amount, value)
# redis_conn.zincrby('goods_rank', 3, 'iphone')
# redis_conn.zincrby('goods_rank', 5, 'huawei')
# redis_conn.zincrby('goods_rank', 2, 'xiaomi')

#
goods_rank = redis_conn.zrange('goods_rank', 0, -1)

print(goods_rank)
for i in goods_rank:
    # a, b = i
    print(i)



